package com.cykj.page02;

import com.cykj.page02.servlet.BaseServlet;
import com.cykj.page02.util.ServletScannerUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.URLDecoder;

/**
 * @BelongsProject: HandTomcat
 * @BelongsPackage: com.cykj.page02
 * @Author: 阿隆
 * @CreateTime: 2025-11-12 20:41
 * @Description: 任务对象
 * @Version: 1.0
 */
public class MyTask implements Runnable {
    //客户端
    private Socket socket;

    public MyTask(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {

//            try {
//                Thread.sleep(800);
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }

            //读取客户端发送的消息
            InputStream is = socket.getInputStream();

            byte[] bytes = new byte[1024];

            //读取
            int len = is.read(bytes);

            //请求消息
            String request = new String(bytes, 0, len);


            System.out.println(request);


            //1.初步解析消息(消息可能不全)
            MyHttpRequest httpRequest = new MyHttpRequest(request);
            //2.判断是不是POST请求
            if ("POST".equals(httpRequest.getRequestMethod())) {
                //3.通过请求头获取总的请求体长度
                int allRequestLength = Integer.parseInt(httpRequest.getRequestHeadToKey("Content-Length"));
                System.out.println("allRequestLength = " + allRequestLength);

                //4.获取当前请求体的长度
                int currentBodyLength = httpRequest.getRequestBody().length();
                System.out.println("currentBodyLength = " + currentBodyLength);
                //5.通过循环读取请求体消息
                while (currentBodyLength < allRequestLength) {
                    //读取消息
                    len = is.read(bytes);
                    //获取消息 并拼接
                    request += new String(bytes, 0, len);

                    currentBodyLength += len;
                }

                //解码
                String decode = URLDecoder.decode(request, "UTF-8");

                //重新解析消息
                httpRequest = new MyHttpRequest(decode);
                System.out.println(decode);


            }

            //响应数据
            MyHttpResponse httpResponse = new MyHttpResponse(socket);

            /*
             * 请求模块: 动态资源 /xxxx
             *           静态资源  资源文件路径  pages/index.html
             * */

            System.out.println("请求模块为: " + httpRequest.getRequestModel());

            //通过注解
            BaseServlet baseServlet = ServletScannerUtils.getServletToRequestModel(httpRequest.getRequestModel());

            //有可能是静态资源 404
            if (baseServlet == null) {
                baseServlet = ServletScannerUtils.getServletToRequestModel("/default");
            }

            baseServlet.requestMethodHandler(httpRequest, httpResponse);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}